<?php
namespace app\wechat\controller;
use app\common\controller\StoreBase;

use app\wechat\model\WechatUser;
use app\wechat\model\WechatTemplate;
use app\wechat\model\WechatTemplateTask;

class Template extends StoreBase
{
    protected $noAuth = ['index','indexs'];
    public function initialize()
    {
        parent::initialize();
        $param = $this->request->param();
    }

    /**
     * 模板列表
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index',[
        ]);
    }
    public function index_json($limit='15')
    {
        $param = $this->request->param();
        $user = new WechatTemplate();
        $list = $user->withCount('task')->order('id desc')->paginate();
        $this->result($list);
    }

    /**
     * 更新模板消息
     */
    public function update()
    {
        WechatTemplate::update_template();
        $this->success('更新成功');
    }

    /**
     * 编辑模板
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($id)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = WechatTemplate::update($param,['id'=>$param['id']]);
            if ($result == true) {
                insert_user_log('修改了模板');
                $this->success('操作成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data = WechatTemplate::where('id',$id)->find();
        //读取列表
        $field = parse_wechat_template($data['content']);
        return $this->fetch('save',[
            'data'   => $data,
            'field'  => $field
        ]);
    }

    /**
     * 任务列表
     * @return mixed
     */
    public function task()
    {
        return $this->fetch('task',[
        ]);
    }
    public function task_json($id,$limit='15')
    {
        $param = $this->request->param();
        $user = new WechatTemplateTask();
        $list = $user->with('user')->where('tid',$id)->order('id desc')->paginate();
        $this->result($list);
    }
    /**
     * 新增发送任务
     * @return mixed
     */
    public function task_add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //先删除旧的发送数据
            WechatTemplateTask::where('tid',$param['tid'])->delete();
            if($param['user_id'] == 0){
                //查询所有用户的OPENID
                $list = WechatUser::where('subscribe',1)->column('id');
                foreach ($list as $k=>$r){
                    $data[$k]['store_id'] = StoreId();
                    $data[$k]['tid']      = $param['tid'];
                    $data[$k]['user_id']  = $r;
                }
                WechatTemplateTask::insertAll($data);
            }else{
                WechatTemplateTask::create([
                    'store_id'  => StoreId(),
                    'tid'       => $param['tid'],
                    'user_id'   => $param['user_id'],
                ]);
            }
            $this->success('操作成功');
        }
        $user = WechatUser::select();
        return $this->fetch('save_task',[
            'user'   => $user
        ]);
    }

    /**
     * 发送任务
     * @param $id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function task_send($id)
    {
        //查询
        $list = WechatTemplateTask::with('user')->where('tid',$id)->where('status',0)->limit(300)->select();
        if(count($list) > 0){
            //读取资料
            $data = WechatTemplate::where('id',$id)->find();
            foreach ($list as $k=>$r){
                $result = WechatTemplate::send_template($data,$r['openid'],$r['id']);
            }
            $this->success('本次发送'.count($list).'条成功,请稍等',url('task_send',['id'=>$id]));
        }else{
            $this->success('发送完成',url('index'));
        }


    }



    
}
